package com.craftplay.service;


import com.alibaba.fastjson.JSON;
import com.craftplay.dao.PayRedPackageMapper;
import com.craftplay.dao.UnitMapper;
import com.craftplay.model.*;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPaySendRedpackRequest;
import com.github.binarywang.wxpay.bean.result.WxPaySendRedpackResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description: 微信Service
 * @Author: JL
 * @CreateDate: 2019/6/17 17:36
 * @Version: 1.0
 */
@Service
public class WeixinService {
    private static final Logger logger = LoggerFactory.getLogger(WeixinService.class);

    @Autowired
    private WxPayService wxService;

    @Autowired
    UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayRedPackageMapper payRedPackageMapper;

    @Autowired
    private UnitMapper unitMapper;


    /**
     * 发送红包
     *
     * @return
     * @throws WxPayException
     */
    public void sendRedpack(Order order) {
        WxPaySendRedpackRequest wxPaySendRedpackRequest = new WxPaySendRedpackRequest();

        Unit unit = unitMapper.selectByPrimaryKey(order.getUnitid());
        String outTradeNo = order.getOuttradeno();

        //获取发送的用户
        User user = userService.selectUserById(unit.getUserId());
        if (user == null) {
            logger.error(outTradeNo + "红包——用户获取失败");
            return;
        }
        //获取支付的订单
        if (order == null) {
            logger.error(outTradeNo + "红包——订单获取失败");
            return;
        }

        //订单号
        Date nowTime = new Date();
        String redOutReadeNo = "JWRP" + (nowTime.getTime()) + unit.getUserId();
        Integer money = (int) (order.getMoney() * 0.95);

        //最少发100分
        if (money < 100) {
            logger.error(outTradeNo + "红包——最少发100分");
            return;
        }
        PayRedPackage payRedPackage = new PayRedPackage();
        payRedPackage.setRedoutreadeno(redOutReadeNo);
        payRedPackage.setOuttradeno(outTradeNo);
        payRedPackage.setUserid(unit.getUserId());
        payRedPackage.setMoney(money);
        payRedPackage.setPaytime(new Date());
        payRedPackage.setCreatetime(new Date());

        String title = unit.getTitle();
        if (unit.getKind() == 10) {
            title = unit.getContent();
        }
        if (title.length() > 8) {
            title = title.substring(0, 8) + "..";
        }

        wxPaySendRedpackRequest.setMchBillNo(redOutReadeNo);
        wxPaySendRedpackRequest.setSendName("Playpro动态解锁");
        wxPaySendRedpackRequest.setReOpenid(user.getOpenId());
        wxPaySendRedpackRequest.setTotalAmount(money);
        wxPaySendRedpackRequest.setTotalNum(1);
        wxPaySendRedpackRequest.setWishing("有人解锁了你的匠玩：" + title);
        wxPaySendRedpackRequest.setClientIp("192.168.20.202");
        wxPaySendRedpackRequest.setActName("红包");
        wxPaySendRedpackRequest.setSceneId("PRODUCT_5");

        try {
            WxPaySendRedpackResult wxPaySendRedpackResult = wxService.sendRedpack(wxPaySendRedpackRequest);
            if ("SUCCESS".equals(wxPaySendRedpackResult.getResultCode())) {
                payRedPackage.setStatus(1);
            } else {
                payRedPackage.setStatus(2);
            }
            payRedPackageMapper.insert(payRedPackage);
        } catch (Exception e) {
            logger.error(e.getMessage());
            payRedPackage.setStatus(2);
            payRedPackageMapper.insert(payRedPackage);
        }
    }


    /**
     * 课程定金发送
     *
     * @return
     * @throws WxPayException
     */
    public void sendClassRedPacket(ClassOrder classOrder) {


        Unit unit = unitMapper.selectByPrimaryKey(classOrder.getUnitId());
        String outTradeNo = classOrder.getOutTradeNo();

        //获取发送的用户
        User user = userService.selectUserById(unit.getUserId());
        if (user == null) {
            logger.error(outTradeNo + "红包——用户获取失败");
            return;
        }

        //订单号
        Date nowTime = new Date();
        Integer money = null;
        //支付定金
        if (classOrder.getClassStatus() == 1) {
            money = (int) (classOrder.getMoney() * 0.1);
            //money = 5000;//默认50块定金

        } else if (classOrder.getClassStatus() == 1) {
            //第三节课全款

        } else {
            return;
        }

        if (money == null) {
            return;
        }
        String redOutReadeNo = "JWCR" + (nowTime.getTime()) + unit.getUserId();
        PayRedPackage payRedPackage = new PayRedPackage();
        payRedPackage.setRedoutreadeno(redOutReadeNo);
        payRedPackage.setOuttradeno(outTradeNo);
        payRedPackage.setUserid(unit.getUserId());
        payRedPackage.setMoney(money);
        payRedPackage.setPaytime(new Date());
        payRedPackage.setCreatetime(new Date());


        EntPayRequest request = new EntPayRequest();
        request.setPartnerTradeNo(redOutReadeNo);
        request.setOpenid(user.getOpenId());
        request.setCheckName("NO_CHECK");
        request.setAmount(money);
        request.setDescription("匠玩课程定金发放");
        request.setSpbillCreateIp("192.168.20.202");

        try {
            payRedPackage.setStatus(3);
            wxService.getEntPayService().entPay(request);
            payRedPackageMapper.insert(payRedPackage);
            logger.info("发送定金:" + money + "_" + unit.getId());
        } catch (WxPayException e) {
            payRedPackage.setStatus(2);
            payRedPackageMapper.insert(payRedPackage);
            e.printStackTrace();
            logger.error("发送定金错误", e);
        }
    }

    /**
     * 课程退款发送
     *
     * @return
     * @throws WxPayException
     */
    public void refundClass(ClassOrder orderDTO) {

        WxPaySendRedpackRequest wxPaySendRedpackRequest = new WxPaySendRedpackRequest();

        //获取发送的用户
        User user = userService.selectUserById(orderDTO.getUserId());
        if (user == null) {
            logger.error(JSON.toJSONString(orderDTO) + "课程退款发送");
            return;
        }

        //订单号
        Date nowTime = new Date();
        String redOutReadeNo = "JWCRT" + (nowTime.getTime()) + orderDTO.getUserId();
        Integer money = orderDTO.getMoney();
        if (money < 0) {
            logger.error(JSON.toJSONString(orderDTO) + "课程退款发送少于0元失败");
            return;
        }

        PayRedPackage payRedPackage = new PayRedPackage();
        payRedPackage.setRedoutreadeno(redOutReadeNo);
        payRedPackage.setOuttradeno(orderDTO.getOutTradeNo());
        payRedPackage.setUserid(orderDTO.getUserId());
        payRedPackage.setMoney(money);
        payRedPackage.setPaytime(new Date());
        payRedPackage.setCreatetime(new Date());

        EntPayRequest request = new EntPayRequest();
        request.setPartnerTradeNo(redOutReadeNo);
        request.setOpenid(user.getOpenId());
        request.setCheckName("NO_CHECK");
        request.setAmount(money);
        request.setDescription("匠玩课程退款");
        request.setSpbillCreateIp("192.168.20.202");

        try {
            payRedPackage.setStatus(4);
            wxService.getEntPayService().entPay(request);
            payRedPackageMapper.insert(payRedPackage);
            logger.info("发送退款:" + money + "_" + orderDTO.getUnitId());
        } catch (WxPayException e) {
            payRedPackage.setStatus(2);
            payRedPackageMapper.insert(payRedPackage);
            logger.error("发送退款错误", e);
        }


    }

    /**
     * 课程尾款支付
     *
     * @return
     * @throws WxPayException
     */
    public void sendEndClass(ClassOrder orderDTO) throws Exception {

        WxPaySendRedpackRequest wxPaySendRedpackRequest = new WxPaySendRedpackRequest();
        Unit unit = unitMapper.selectByPrimaryKey(orderDTO.getUnitId());
        String outTradeNo = orderDTO.getOutTradeNo();

        //获取发送的用户
        User user = userService.selectUserById(unit.getUserId());
        if (user == null) {
            logger.error(outTradeNo + "红包——用户获取失败");
            return;
        }
        //订单号
        Date nowTime = new Date();
        String redOutReadeNo = "JWCEC" + (nowTime.getTime()) + orderDTO.getUserId();
        Integer money = (int) (orderDTO.getMoney() * 0.85) - (int) (orderDTO.getMoney() * 0.1);//减去押金50块
        if (money == null || money < 100) {
            throw new Exception();
        }

        PayRedPackage payRedPackage = new PayRedPackage();
        payRedPackage.setRedoutreadeno(redOutReadeNo);
        payRedPackage.setOuttradeno(orderDTO.getOutTradeNo());
        payRedPackage.setUserid(orderDTO.getUserId());
        payRedPackage.setMoney(money);
        payRedPackage.setPaytime(new Date());
        payRedPackage.setCreatetime(new Date());


        EntPayRequest request = new EntPayRequest();
        request.setPartnerTradeNo(redOutReadeNo);
        request.setOpenid(user.getOpenId());
        request.setCheckName("NO_CHECK");
        request.setAmount(money);
        request.setDescription("匠玩课程尾款");
        request.setSpbillCreateIp("192.168.20.202");

        try {
            payRedPackage.setStatus(5);
            wxService.getEntPayService().entPay(request);
            payRedPackageMapper.insert(payRedPackage);
            logger.info("发送尾款:" + money + "_" + orderDTO.getUnitId());
        } catch (WxPayException e) {
            payRedPackage.setStatus(2);
            payRedPackageMapper.insert(payRedPackage);
            logger.error("发送尾款错误", e);
        }


    }

}
